<template>
  <div class="role-container">
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="search.roleName" placeholder="角色名称" clearable @keyup.enter="searchRole">
            <template #append>
              <el-button @click="searchRole">搜索</el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="search.status" placeholder="角色状态">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6" style="text-align: right">
          <el-button type="primary" @click="addRole">
            <el-icon><Plus /></el-icon>新增角色
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="table-card">
      <el-table
        :data="roleList"
        stripe
        border
        fit
        highlight-current-row>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleCode" label="角色编码"></el-table-column>
        <el-table-column prop="description" label="角色描述"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleStatusChange(scope.row.id, scope.row.status)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editRole(scope.row)">编辑</el-button>
            <el-button size="small" type="warning" @click="setPermissions(scope.row)">权限设置</el-button>
            <el-button size="small" type="danger" @click="deleteRole(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        style="margin-top: 20px; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total">
      </el-pagination>
    </el-card>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="角色管理">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="formData.roleCode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formData.description" type="textarea" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" active-value="1" inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog :visible.sync="permissionDialogVisible" title="权限设置">
      <div class="permission-container">
        <el-tree
          :data="permissionList"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          :props="treeProps">
        </el-tree>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermissions">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog :visible.sync="deleteDialogVisible" title="提示">
      <template #content>
        <p>确定要删除该角色吗？</p>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRoles, addRole, updateRole, deleteRole as apiDeleteRole, getPermissions, setRolePermissions } from '@/api/role'

// 搜索条件
const search = reactive({
  roleName: '',
  status: ''
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 角色列表
const roleList = ref([])

// 权限列表
const permissionList = ref([])

// 对话框状态
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const formRef = ref(null)
const formData = reactive({
  id: null,
  roleName: '',
  roleCode: '',
  description: '',
  status: '1'
})

// 当前角色ID
const currentRoleId = ref(null)

// 已选择的权限
const checkedPermissions = ref([])

// 表单验证规则
const formRules = reactive({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' }
  ]
})

// 树配置
const treeProps = ref({
  label: 'name',
  children: 'children'
})

// 当前要删除的角色ID
const currentDeleteId = ref(null)

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      roleName: search.roleName,
      status: search.status
    }

    const res = await getRoles(params)
    roleList.value = res.data.list
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取角色列表失败', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 获取权限列表
const fetchPermissionList = async () => {
  try {
    const res = await getPermissions()
    permissionList.value = res.data
  } catch (error) {
    console.error('获取权限列表失败', error)
    ElMessage.error('获取权限列表失败')
  }
}

// 搜索角色
const searchRole = () => {
  pagination.currentPage = 1
  fetchRoleList()
}

// 分页相关方法
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchRoleList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchRoleList()
}

// 新增角色
const addRole = () => {
  formData.id = null
  formData.roleName = ''
  formData.roleCode = ''
  formData.description = ''
  formData.status = '1'

  dialogVisible.value = true

  nextTick(() => {
    formRef.value.resetFields()
  })
}

// 编辑角色
const editRole = (row) => {
  formData.id = row.id
  formData.roleName = row.roleName
  formData.roleCode = row.roleCode
  formData.description = row.description
  formData.status = row.status.toString()

  dialogVisible.value = true

  nextTick(() => {
    formRef.value.resetFields()
  })
}

// 保存角色
const saveRole = () => {
  formRef.value.validate(valid => {
    if (valid) {
      const params = { ...formData }

      if (formData.id) {
        // 更新角色
        updateRole(params).then(() => {
          ElMessage.success('更新角色成功')
          dialogVisible.value = false
          fetchRoleList()
        }).catch(error => {
          console.error('更新角色失败', error)
          ElMessage.error('更新角色失败')
        })
      } else {
        // 新增角色
        addRole(params).then(() => {
          ElMessage.success('新增角色成功')
          dialogVisible.value = false
          fetchRoleList()
        }).catch(error => {
          console.error('新增角色失败', error)
          ElMessage.error('新增角色失败')
        })
      }
    } else {
      console.log('验证失败')
      return false
    }
  })
}

// 删除角色
const deleteRole = (id) => {
  currentDeleteId.value = id
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = () => {
  apiDeleteRole(currentDeleteId.value).then(() => {
    ElMessage.success('删除角色成功')
    deleteDialogVisible.value = false
    fetchRoleList()
  }).catch(error => {
    console.error('删除角色失败', error)
    ElMessage.error('删除角色失败')
  })
}

// 设置权限
const setPermissions = (row) => {
  currentRoleId.value = row.id

  // 获取角色已有的权限
  getRolePermissions(row.id).then(res => {
    checkedPermissions.value = res.data || []
    permissionDialogVisible.value = true
  }).catch(error => {
    console.error('获取角色权限失败', error)
    ElMessage.error('获取角色权限失败')
  })
}

// 获取角色权限
const getRolePermissions = (roleId) => {
  return new Promise((resolve, reject) => {
    // 这里应该调用API获取角色权限
    // 为了演示，使用模拟数据
    setTimeout(() => {
      resolve({ data: [1, 2, 5, 6, 10] })
    }, 300)
  })
}

// 保存权限
const savePermissions = () => {
  const params = {
    roleId: currentRoleId.value,
    permissionIds: checkedPermissions.value
  }

  setRolePermissions(params).then(() => {
    ElMessage.success('权限设置成功')
    permissionDialogVisible.value = false
  }).catch(error => {
    console.error('权限设置失败', error)
    ElMessage.error('权限设置失败')
  })
}

// 处理角色状态变更
const handleStatusChange = (id, status) => {
  ElMessageBox.confirm(
    `确定要${status ? '启用' : '禁用'}该角色吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    updateRole({ id, status: status ? 1 : 0 }).then(() => {
      ElMessage.success('更新角色状态成功')
    }).catch(() => {
      // 回滚状态
      const role = roleList.value.find(item => item.id === id)
      if (role) {
        role.status = !status
      }
    })
  }).catch(() => {
    // 回滚状态
    const role = roleList.value.find(item => item.id === id)
    if (role) {
      role.status = !status
    }
  })
}

onMounted(() => {
  fetchRoleList()
  fetchPermissionList()
})
</script>

<style scoped>
.role-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  min-height: 400px;
}

.permission-container {
  max-height: 400px;
  overflow-y: auto;
}
</style>
